﻿using System;
using System.IO;
using System.Xml.Serialization;
using Ultra_Presenter.Model;

namespace Ultra_Presenter.Util
{
    /// <summary>
    /// Class for serialization.
    /// </summary>
    public class SerializationHelper
    {
        /// <summary>
        /// Serialize objects to file.
        /// </summary>
        /// <param name="p"> Project to be serialized.</param>
        /// <param name="path">Path to file.</param>
        public static void Serialize(Project p, string path)
        {
            XmlSerializer ser = new XmlSerializer(p.GetType());
            {
                using (StreamWriter writer = new StreamWriter(path))
                {
                    ser.Serialize(writer, p);
                }
            }
        }

        /// <summary>
        /// Deserialize file to objects.
        /// </summary>
        /// <param name="path">Path to file.</param>
        /// <returns>Object of Project.</returns>
        public static Project Deserialize(string path)
        {
            Project p = null;

            try
            {
                XmlSerializer x = new XmlSerializer(typeof(Project));
                {
                    using (StreamReader reader = new StreamReader(path))
                    {
                        p = (Project)x.Deserialize(reader);
                    }
                }
            }
            catch
            {
                throw new Exception("This file is not correct. Try another one!");
            }

            return p;
        }
    }
}
